<template>
    <div class="tableRow">
        <div style="flex: 1">
            <el-card shadow="never">
                <div slot="header"
                    style="display: flex;align-items: center;justify-content: space-between;height: 30px;">
                    <div class="radio-t">
                        <div class="haz-header">{{ headerTitle }}</div>
                    </div>
                    <div class="radio-t">

                        <el-button v-if="dataType == '0'" type="success" icon="el-icon-s-promotion" size="small"
                            style="margin-right: 10px;" plain @click="submitHandler('1')"
                            v-permission="'bus:data:edit'">提交</el-button>
                        <el-button v-if="dataType == '1'" type="success" icon="el-icon-s-promotion" size="small"
                            style="margin-right: 10px;" plain @click="submitUpdateHandler('1')"
                            v-permission="'bus:data:edit'">核实更新</el-button>
                        <el-button v-if="dataType == '1'" type="success" icon="el-icon-s-promotion" size="small"
                            style="margin-right: 10px;" plain @click="submitNotChangeHandler('1')"
                            v-permission="'bus:data:edit'">核实不变</el-button>
                        <el-button  v-if="dataType == '2'" type="primary" icon="el-icon-success" size="small" plain
                            v-permission="'bus:data:edit'" @click="submitMapHandler()"
                            style="margin-right: 10px;">保存地理数据</el-button>
                        <el-button v-else type="primary" icon="el-icon-success" size="small" plain
                            v-permission="'bus:data:edit'" @click="submitHandler('0')"
                            style="margin-right: 10px;">保存</el-button>
                        <el-button v-if="dataType == '1'"  type="danger" icon="el-icon-delete" size="small" plain v-permission="'bus:data:edit'"
                            @click="cancelHandler" style="margin-right: 10px;">取消 </el-button>
                        <el-button type="primary" icon="el-icon-success" size="small" plain
                            v-permission="'bus:data:edit'" @click="backDataUpdateHandler" style="margin-right: 10px;">
                            返回</el-button>
                    </div>
                </div>
                <el-row style="height: 100vh">
                    <el-col :span="12" class="box-right">
                        <open-map mapWidth="100%" mapHeight="100vh" ref="areaMap" @polygonChange="polygonAreaHandler"
                            @positionChange="positionChangeHandler" :vectorId="models.formData.vectorId"
                            :polygon="models.formData.polygon" :position="models.position"
                            @polygonLoaded="polygonLoadedHandler">
                            <template #card>
                                <div class="boundary-right">
                                    <el-tree-select v-model="models.formData.areaId" size="small"
                                        style="float: left;margin-right: 10px;" :selectParams="dialog.areaSelectParams"
                                        :treeParams="dialog.areaTreeParams" ref="areaTreeSelect"
                                        @node-click="checkAreaHandler" />
                                    <el-select v-model="models.formData.departId"
                                        style="margin-right: 10px;height: 40px;" placeholder="请选择调查对象" ref="deptSelect"
                                        @change="checkDeptHandler">
                                        <el-option-group v-for="group in dialog.deptData" :key="group.label"
                                            :label="group.label">
                                            <el-option v-for="item in group.options" :key="item.id" :label="item.label"
                                                :value="item.id">
                                            </el-option>
                                        </el-option-group>

                                    </el-select>
                                    <el-button type="primary" size="small" plain @click="searchPlaceHandler"
                                        style="margin-right: 10px;">搜索</el-button>
                                    <el-input v-if="showSearch" suffix-icon="el-icon-search" v-model="searchName"
                                        clearable @click.native="startSearch"></el-input>

                                    <ul v-if="showSearch && suggestions" id="suggestions-list"
                                        style="z-index: 10000;background-color: aliceblue;">
                                        <li v-for="(item, index) of suggestions" :key="index"
                                            @click="selectPlace(item)">
                                            {{ item.name }}
                                        </li>
                                    </ul>
                                    <place-card ref="placeCard"
                                        style="width: 0px; height: 0px;display: none;"></place-card>
                                </div>

                                <div class="boundary-bottom ">
                                    <el-row>
                                        <el-col>坐标：<span @click="moveToPositionHandler">{{ models.formData.point
                                                }}</span></el-col>
                                        <el-col>面积：{{ polygonArea }} 平方米</el-col>
                                        <el-col>经度：<el-input size="mini" v-model="jingdu" style="width:150px;color: #1e00ff;font-weight: 1000;"></el-input> 纬度: <el-input v-model="weidu" size="mini" style="font-weight: 1000;width:150px;color: #1e00ff;"></el-input><el-button size="mini" @click="locationHandler">搜索</el-button></el-col>
                                    </el-row>
                                </div>
                            </template>
                        </open-map>
                    </el-col>
                    <el-col :span="12">
                        <survey-model ref="surveyComp" :showHistory="true" :structureId="models.queryData.structureId"
                            :key="models.queryData.structureId" :isEdit="true" tableHeight="50vh"></survey-model>
                    </el-col>
                </el-row>
            </el-card>
        </div>
    </div>
</template>
<script lang="ts">
import { Component, Vue, Ref, Watch } from 'vue-property-decorator';
import router from '@/router/index';
import OpenMap from '@/components/OpenMap.vue';
import SurveyModel from '@/components/SurveyModel.vue';
import { userWorkAreaTreeSelectData } from '@/api/areaManager';
import { selectInvestObject } from '@/api/dept';
import { getFormData, removeDataCommon ,updateDataCommon} from '@/api/investDataCommon';
import PlaceCard from "@/views/region/components/PlaceCard.vue";
import { baiduSearch, findAddress } from '@/api/dataSearch';
import school from '@/assets/geojson/school.json';
import hospital from '@/assets/geojson/hospital.json';
import manzhouli from '@/assets/geojson/manzhouli.json';


@Component({ components: { SurveyModel, OpenMap, PlaceCard } })
export default class surveyAdd extends Vue {

    @Ref("surveyComp") surveyComp!: any;
    @Ref("areaTreeSelect") areaTreeSelect!: any;
    @Ref("deptSelect") deptSelect!: any;
    @Ref("areaMap") areaMap!: any;
    @Ref("placeCard") placeCard!: any;
    headerTitle: any = "";
    searchName: any = "";
    suggestions: any = null;
    private dataType = '0';

    showSearch: any = false;
    school = school;
    hospital = hospital;
    manzhouli = manzhouli;
    polygonArea = 0;
    jingdu ='';
    weidu ='';


    models: any = {

        queryData: {
            structureId: '',
            departId: '',
            id: '',
        },
        deptQuery: {
            areaId: '',
            categoryId: ''
        },
        formData: {
            areaId: '',
            departId: '',
            polygon: '',
            status: '0',
            vectorId: '',
            point: '',
        },
        position: null,

    }

    dialog: any = {
        deptData: [],
        deptIdMap: {},
        dialogFormVisible: false,
        title: '对话框',
        isEdit: false,
        isBatchEditDisabled: true,
        isBatchRemoveDisabled: true,

        areaSelectParams: {
            clearable: true,
            placeholder: '请选择区划'
        },
        areaTreeParams: {
            clickParent: true,
            filterable: false,
            accordion: true,
            data: [],
            props: {
                children: 'children',
                label: 'label',
                disabled: 'disabled',
                value: 'id'
            }
        }
    };

    positionChangeHandler(val) {
        if (val && val.length > 0) {
            this.models.formData.point = val.join(',');
        }
    }

    departOptionHandler(val) {
       console.log(val);
    }

    locationHandler(){
        if(!this.jingdu){
            this.$message.error("请输入经度");
            return;
        }
        if(!this.weidu){
            this.$message.error("请输入纬度");
            return;
        }
        const lng = parseFloat(this.jingdu);
        if(isNaN(lng) ){
            this.$message.error("输入的经度不是数字");
            return;
        }

        const lat = parseFloat(this.weidu);
        if(isNaN(lat) ){
            this.$message.error("输入的纬度不是数字");
            return;
        }
        this.areaMap.updatePosition([lng, lat]);
    }
    parseCoordinates(input) {
        try {
            // 尝试解析为数组格式
            if (input.startsWith('[') && input.endsWith(']')) {
                const arr = JSON.parse(input)
                if (Array.isArray(arr) && arr.length === 2 &&
                    typeof arr[0] === 'number' && typeof arr[1] === 'number') {
                    return arr
                }
            }

            // 处理各种分隔符
            const separator = input.includes('，') ? '，' :
                input.includes(',') ? ',' :
                    input.includes(' ') ? ' ' : null;

            if (separator) {
                const parts = input.split(separator).map(part => part.trim())
                if (parts.length === 2) {
                    const lng = parseFloat(parts[0])
                    const lat = parseFloat(parts[1])

                    if (!isNaN(lng) && !isNaN(lat)) {
                        return [lng, lat]
                    }
                }
            }

            return null
        } catch (e) {
            return null
        }
    }

    polygonAreaHandler(area) {
      
        this.polygonArea = area;
    }

    searchPlaceHandler() {
        this.showSearch = this.showSearch ? false : true;
    }

    isLatLong(str) {
        const [lat, long] = str.split(',');
        if (isNaN(lat) || isNaN(long)) {
            return false;
        }
        return true;
    }

    startSearch(event) {
        if (!event.target.classList.contains('el-input__icon')) {
            return;
        }
        if (!this.models.formData.areaId) {
            this.$message.error("请先选择区划然后进行搜索");
            return;
        }

        const name = this.searchName;
        const location = this.parseCoordinates(name);
        if (location) {
            this.$message.success("正在搜索经纬度");
            this.models.position = location;
            return;
        }
        this.$message.success("正在搜索请稍等");

        if (this.models.formData.areaId) {
            this.selectPlace({ 'name': name });
            baiduSearch({ 'name': name, 'areaId': this.models.formData.areaId }).then(res => {

                if (res && res.data && res.data.results) {
                    this.suggestions = res.data.results.filter(s => s.location);
                    if (this.suggestions.length > 0) {
                        this.placeCard.cityPoint(this.suggestions);
                    }

                } else {
                    this.suggestions = null;
                }

            }).catch(e => {
                this.suggestions = null;


            })
        }
    }

    submitMapHandler() {
        const polygon = this.areaMap.getPolygon();

        updateDataCommon({id: this.models.queryData.id, polygon: polygon ,point:this.models.formData.point}).then(res => {
            this.$message.success("更新成功");
        }).catch(e => {
            this.$message.error("更新失败" + e);
        })
    }

    selectPlace(item: any) {
        if (item.location) {
            const feature: any = school.features.find(ft => {

                if (ft.properties.name.includes(item.name)) {
                    return true;
                }
                return false;
            });
            const featureH:any = hospital.features.find(ft => {

                if (ft.properties.name.includes(item.name)) {
                    return true;
                }
                return false;
            });
            if (feature) {
                feature.id = "11"
                this.areaMap.addPolygonSource(feature);
                // this.models.formData.polygon =  JSON.stringify(feature.geometry.coordinates[0]);
            }
            if (featureH) {
                featureH.id = "12";
                this.areaMap.addPolygonSource(featureH);
                //this.models.formData.polygon =  JSON.stringify(featureH.geometry.coordinates[0]);
            }
            const posi = [item.location.lng, item.location.lat];
            console.log(this);
            this.models.position = posi;
            this.models.formData.point = item.location.lng + "," + item.location.lat;

        } else {
            const manzhouL = manzhouli.features.find(ft => {

                if (ft.properties.Name.includes(item.name)) {
                    return true;
                }
                return false;
            });


            if (manzhouL) {
                
                console.log(manzhouL)
                if(manzhouL.geometry.type == 'Point'){
                        const posi = [manzhouL.geometry.coordinates[1], manzhouL.geometry.coordinates[0]];
                        console.log(this);
                        this.models.position = posi;
                }else{
                    this.models.position = manzhouL.geometry.coordinates[0];
                    this.areaMap.addPolygonSource(manzhouL);
                }
               
            }
        }

    }

    generateSequence = (length: number, pre: string): string[] => {
        return Array.from({ length: length }, (_, i) => {
            const number = i + 1;
            const prefix = (number > 9 ? '' : '0');
            return pre + prefix + number.toString();
        });
    }
    areaSearchFun(value: any): void {
        this.areaTreeSelect.filterFun(value);
    }

    backDataUpdateHandler() {
        this.$destroy();
        this.$router.go(-1);
    }

    moveToPositionHandler() {
        if (this.models.formData.point) {
            this.areaMap.updatePosition(this.models.formData.point.split(','));
        }

    }

    submitUpdateHandler(status) {
        this.models.formData.changeStatus = '2';
        this.submitHandler(status);

    }

    submitNotChangeHandler(status) {

        this.models.formData.changeStatus = '1';
        this.models.formData.status = status;
        this.surveyComp.handleSubmit(this.models.formData, status);
    }

    submitHandler(status) {

        if (router.currentRoute.query.polygon === '1') {
            const polygon = this.areaMap.getPolygon();

            if (polygon) {
                this.models.formData.polygon = polygon;
            } else {
                this.$message.error("此调查需要绘制区域，请绘制");
                return;
            }
        }
        if (!this.models.formData.point) {
            this.$message.error("请进行定位");
            return;
        }

        if (status) {
            this.models.formData.status = status;
        }

        this.surveyComp.handleSubmit(this.models.formData, status);

    }

    cancelHandler() {
        this.handleBatchDelete(this.models.queryData.id)
    }

    getDeptTree() {
        selectInvestObject(this.models.deptQuery).then(res => {
            this.dialog.deptData = res.data;
            this.dialog.deptData.forEach((group: any) => {
                group.options.forEach(op => {
                    this.dialog.deptIdMap[op.id] = op;
                    if (op.checked) {
                        this.models.formData.departId = op.id;
                    }
                })
            });
        });
    }


    handleBatchDelete(id) {
        //删除
        this.$confirm('确定要删除选定数据吗？', '警告', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
        }).then(() => {
            return removeDataCommon({ 'ids': [id] });
        }).then((response: any) => {
            this.$message.success(response.msg);
            this.$router.back();
        }).catch((e) => {
            console.error(e);
        });
    }

    checkAreaHandler(area: any, node: any, vm: any) {
        if (area) {
            this.models.formData.areaId = area.id;
            this.models.formData.vectorId = area.vectorId;
            this.models.deptQuery.areaId = area.id;
            let ps = area.position;

            if (ps) {
                this.models.position = ps;
            }
            this.models.formData.departId = '';
            this.getDeptTree();

        } else {
            this.models.formData.departId = null;
        }
    }

    checkDeptHandler(id: number) {
        let opt = this.dialog.deptIdMap[id];
        this.surveyComp.updateHeadCode('head01', opt.code);
        this.surveyComp.updateHeadCode('head04', opt.label);
        this.surveyComp.updateCode('code01', opt.label);

        findAddress({ areaId: this.models.formData.areaId, name: opt.label }).then(res => {
            if (res && res.data && res.data.location) {
                this.areaMap.updatePosition(res.data.location.split(','));
            }
        }).catch(e => {
            console.error(e);
        })
    }


    created() {
        if (!router.currentRoute.query.id) {

            this.models.queryData.structureId = router.currentRoute.query.structureId;
            this.models.deptQuery.categoryId = router.currentRoute.query.categoryId;
            this.models.formData.workId = router.currentRoute.query.workId;
            this.headerTitle = router.currentRoute.query.workName + "/" + router.currentRoute.query.categoryName;
            this.changeData();
        }

    }
    @Watch('$route.query.id', { immediate: true })
    routerChangeHandler(val) {

        if (val) {

            this.models.queryData.structureId = router.currentRoute.query.structureId;
            if (router.currentRoute.query.id) {
                this.models.queryData.id = router.currentRoute.query.id;
            }

            this.models.deptQuery.categoryId = router.currentRoute.query.categoryId;
            this.models.formData.workId = router.currentRoute.query.workId;

            this.headerTitle = router.currentRoute.query.workName + "/" + router.currentRoute.query.categoryName;
            this.changeData();
        }

    }


    polygonLoadedHandler() {
        this.placeCard.initClickInteraction(this.areaMap.models.map);
    }
    changeData() {
   
        userWorkAreaTreeSelectData({ workId: this.models.formData.workId }).then(res => {
            this.dialog.areaTreeParams.data = res.data;
            this.areaTreeSelect.treeDataUpdateFun(res.data);
        })

        if (this.models.queryData.id) {
            this.getDataCommon();
        }

    }
    getDataCommon() {
        getFormData({ id: this.models.queryData.id }).then(res => {

            const common: any = res.data.commonForm;
            this.dataType = common.dataType;
            this.models.formData.areaId = common.areaId;
            this.models.deptQuery.areaId = common.areaId;
            this.getDeptTree();
            this.models.formData.vectorId = common.vectorId;
            this.models.formData.departId = common.departId;
            if (common.position) {

                this.models.formData.point = common.position;
                this.areaMap.updatePosition(common.position.split(','));
            }

            this.models.formData.polygon = common.polygon;
            this.surveyComp.addFormData(res.data);
        })
    }

    mounted() {
        (this as any).$bus.$on('refreshData', () => {
            this.getDataCommon();
        });
    }
}
</script>
<style scoped>
.el-input__inner {
    height: 30px;
}

.data-tool {
    .el-input {
        float: right;
    }
}

.haz-header {
    height: 28px;
    line-height: 28px;
    color: #448f7d;
    padding-left: 18px;
    border-left: 3px solid #448f7d;
    font-size: 14px;
    font-weight: bold;
    background: linear-gradient(to right, #e1f5f1, rgba(255, 255, 255, 1));
}


::v-deep .el-card .el-card__header {
    padding: 6px 10px !important;
}

::v-deep .el-card__body {
    padding: 0px 5px 0px 5px !important;
}

::v-deep .box-right {
    flex: 1;
    position: relative;


}

.boundary-right {
    background-color: #fff;
    position: absolute;
    padding: 10px;
    top: 30px;
    left: 18px;
    z-index: 1000;
}

.boundary-bottom {
    /* background-color: #fff; */
    position: absolute;
    padding: 10px;
    bottom: 120px;
    left: 18px;
    color: #1e00ff;
    opacity: 0.4;
    z-index: 1000;
    font-weight: 1000;
}

#search-container {
    margin-bottom: 10px;
}

#suggestions-list {
    list-style: none;
    padding: 0;
    margin: 0;
    max-height: 200px;
    overflow-y: auto;
    border: 1px solid #ccc;
}

#suggestions-list li {
    padding: 8px;
    cursor: pointer;
}

#suggestions-list li:hover {
    background-color: #f0f0f0;
}

#map-container {
    width: 100%;
    height: 500px;
    margin-top: 20px;
}
</style>
